#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import time

from Atm.core import db_handler
from Atm.core import accounts

def login_required(func):
    '''验证用户是否登录'''
    def wrapper(*args, **kwargs):
        if args[0].get('is_authenticated'):
            return func(*args, **kwargs)
        else:
            exit('你的账号没有通过身份认证...')
    return wrapper

def acc_auth(account, password):
    '''
    验证用户名密码
    :param account:
    :param password:
    :return: 返回用户数据
    '''
    acc_data = accounts.load_current_balance(account)
    if acc_data:
        if acc_data['status'] == 0:
            if acc_data['password'] == password:
                expire_date = time.mktime(time.strptime(acc_data['expire_date'], "%Y-%m-%d"))
                if time.time() > expire_date:   # 判断卡片过期时间是小于当前时间
                    print('你的卡片已过期,请换发新卡片...')
                else:
                    return acc_data
            else:
                print('用户名或密码错误...')
        elif acc_data['status'] == 1:
            print('你的卡片被冻结...')
        elif acc_data['status'] == 2:
            print('你的卡片已注销...')
    else:
        print('%s 用户不存在' % account)

def acc_login(user_data):
    '''
    用户登录函数
    :param user_data:
    :return: 用户数据
    '''
    retry_count = 0
    while user_data['is_authenticated'] is not True and retry_count < 3:
        account = input('请输入账号:').strip()
        password = input('请输入密码:').strip()
        auth = acc_auth(account, password)  # 验证用户名密码
        if auth:
            user_data['is_authenticated'] = True
            user_data['account_id'] = account
            return auth
        retry_count += 1

def acc_check(account_id):
    '''
    判断用户是否存在
    :param account_id:
    :return:
    '''
    account_data = accounts.load_current_balance(account_id)
    if account_data:
        expire_date = time.mktime(time.strptime(account_data['expire_date'], "%Y-%m-%d"))   # 获取过期时间
        if time.time() > expire_date:
            print('你的卡片已过期,请换发新卡片...')
        else:
            return account_data
